import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:sptapp/api/interface/login_api.dart';
import 'package:sptapp/basic/base_info.dart';
import 'package:sptapp/utils/regex_tool.dart';

import '../../api/request/response_data.dart';
import '../../config/const.dart';
import '../../data/user_info_entity.dart';
import '../../moudle/message.dart';
import '../../widget/common_widget.dart';
import '../index_drawer_page.dart';

class RegisterPage extends StatefulWidget {
  const RegisterPage({super.key});

  @override
  State<RegisterPage> createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {

  String? firstName;
  String? lastName;
  String? password;
  String? surePassword;
  String? mail;
  String? code;
  bool isDisabled = true;
  bool isSureDisabled = true;

  Timer? _countdownTimer;
  int _countdownNum = 60;
  late String codeText;

  bool isDone = false;

  TextEditingController firstNameController = TextEditingController();
  TextEditingController lastNameController = TextEditingController();
  TextEditingController mailController = TextEditingController();
  TextEditingController codeController = TextEditingController();
  TextEditingController passwordController = TextEditingController();
  TextEditingController surePasswordController = TextEditingController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    codeText = get_code_btn.tr;
  }

  /// 获取验证码
  void getMsgCode() async {
    if(mail == null || mail!.isEmpty){
      showToast(mail_hintText.tr);
      return;
    }
    if(validateEmail(mail!) == false){
      showToast(email_input_error.tr);
      return;
    }
    if(_countdownNum != 60){
      return;
    }
    if (mail == null || mail!.isEmpty) {
      showToast(mail_hintText.tr);
      return;
    }
    showLoading();
    ResponseData res = await LoginAPI.sendCode(mail!);
    hideLoading();
    if (res.code == 200) {
      startCountDownTimer();
    }
  }

  /// 开始倒计时
  startCountDownTimer() {
    if(_countdownTimer != null){
      _countdownTimer?.cancel();
      _countdownTimer = null;
      _countdownNum = 60;
      codeText = get_code_btn.tr;
    }
    _countdownTimer = Timer.periodic(new Duration(seconds: 1), (timer) {
      setState(() {
        if (_countdownNum > 0) {
          codeText = "${_countdownNum--}s";
        } else {
          _countdownTimer?.cancel();
          _countdownTimer = null;
          _countdownNum = 60;
          codeText = get_code_btn.tr;
        }
      });
    });
  }

  getIsDone(){
    if( lastName == null || lastName!.isEmpty || firstName == null || firstName!.isEmpty || password == null || password!.isEmpty || surePassword == null || surePassword!.isEmpty || mail == null || mail!.isEmpty || code == null || code!.isEmpty){
      isDone = false;
    }else{
      isDone = true;
    }
    if(mounted){
      setState(() {});
    }
  }

  _register()async{
    if(validateEmail(mail!) == false){
      showToast(email_input_error.tr);
      return;
    }
    if(password!.length<6 || surePassword!.length < 6){
      showToast(pwd_length_less.tr);
      return;
    }
    if(password! != surePassword!){
      showToast('Invalid password, please re-enter'.tr);
      return;
    }
    Map<String,dynamic> data = {
      'email':mail,
      'nickname':'$firstName$lastName',
      'firstName':firstName,
      'lastName':lastName,
      'password':password,
      'smscode':code,
      'confirmPassword':surePassword
    };
    showLoading();
    ResponseData res = await LoginAPI.register(data);
    hideLoading();
    if(res.code == 200){
      LocalBaseInfo.setAccount(mail!);
      // showToast(regisert_success.tr);
      // Navigator.of(context).pop();
      _login();
    }
  }

  _login()async{
    showLoading();
    ResponseData res = await LoginAPI.login({
      'username':mail,
      'password':password
    });
    hideLoading();
    if(res.code == 200){
      LocalBaseInfo.setToken(res.data['token']);
      LocalBaseInfo.setAccount(mail!);
      Navigator.pushAndRemoveUntil(context, PageRouteBuilder(
          settings: const RouteSettings(name: "index"),
          pageBuilder:
              (BuildContext context, Animation animation,
              Animation secondaryAnimation) {
            return const DrawerIndexPage();
          }), (route) => false);
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _countdownTimer?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: defaultBlackBgColor,
      body: Container(
        padding: EdgeInsets.symmetric(horizontal: 48.w),
        child: Column(
          children: [
            Expanded(child: GestureDetector(
              onTap: (){
                getIsDone();
                FocusScope.of(context).requestFocus(FocusNode());
              },
              child: SingleChildScrollView(
                child: Container(
                  alignment: Alignment.center,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      SizedBox(height:160.w,),
                      Container(
                        alignment: Alignment.centerLeft,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Visibility(child: GestureDetector(
                              onTap: (){
                                Navigator.of(context).pop();
                              },
                              child: Container(
                                child: Image.asset('assets/login/back.png',width: 56.w,),
                              ),
                            ),visible: true,),
                            SizedBox(height: 28.w,),
                            Container(
                              child: Text('Sign Up'.tr,style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 48.sp,
                                  fontWeight: FontWeight.w600
                              ),maxLines: 1,overflow: TextOverflow.ellipsis,),
                            )
                          ],
                        ),
                      ),
                      SizedBox(height: 90.w,),
                      //用户名
                      Container(
                        width: 670.w,
                        height: 108.w,
                        padding: EdgeInsets.symmetric(horizontal: 30.w),
                        decoration: BoxDecoration(
                            border: inputBorder,
                            borderRadius: BorderRadius.circular(20.w)
                        ),
                        child:  Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Expanded(child: TextField(
                              //控制器
                              textInputAction: TextInputAction.done,
                              controller: firstNameController,
                              maxLength: 20,
                              maxLines: 1,
                              //是否自动更正
                              autocorrect: true,
                              //是否自动对焦
                              autofocus: false,
                              style: inputStyle,
                              inputFormatters: [

                              ],
                              decoration: InputDecoration(
                                contentPadding: const EdgeInsets.symmetric(vertical: 0,horizontal: 0),
                                hintText: 'First Name'.tr,
                                hintStyle: inputHitStyle,
                                counterText: "",
                                border: OutlineInputBorder(
                                    borderSide: BorderSide.none),
                              ),
                              onChanged: (val){
                                setState(() {
                                  firstName = val.trim();
                                });
                                getIsDone();
                              },
                            )),
                            SizedBox(width: 20.w,),
                            Visibility(visible: firstName!=null&&firstName!.isNotEmpty,
                              child: GestureDetector(
                                onTap: (){
                                  setState(() {
                                    firstNameController.text = '';
                                    firstName = null;
                                  });
                                  getIsDone();
                                },
                                child: Container(
                                  child: inputImg,
                                ),
                              ),
                            )
                          ],
                        ),
                      ),
                      SizedBox(height: 32.w,),
                      //Last Name
                      Container(
                        width: 670.w,
                        height: 108.w,
                        padding: EdgeInsets.symmetric(horizontal: 30.w),
                        decoration: BoxDecoration(
                            border: inputBorder,
                            borderRadius: BorderRadius.circular(20.w)
                        ),
                        child:  Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Expanded(child: TextField(
                              //控制器
                              textInputAction: TextInputAction.done,
                              controller: lastNameController,
                              maxLength: 20,
                              maxLines: 1,
                              //是否自动更正
                              autocorrect: true,
                              //是否自动对焦
                              autofocus: false,
                              style: inputStyle,
                              inputFormatters: [

                              ],
                              decoration: InputDecoration(
                                contentPadding: const EdgeInsets.symmetric(vertical: 0,horizontal: 0),
                                hintText: 'Last Name'.tr,
                                hintStyle: inputHitStyle,
                                counterText: "",
                                border: OutlineInputBorder(
                                    borderSide: BorderSide.none),
                              ),
                              onChanged: (val){
                                setState(() {
                                  lastName = val.trim();
                                });
                                getIsDone();
                              },
                            )),
                            SizedBox(width: 20.w,),
                            Visibility(visible: lastName!=null&&lastName!.isNotEmpty,
                              child: GestureDetector(
                                onTap: (){
                                  setState(() {
                                    lastNameController.text = '';
                                    lastName = null;
                                  });
                                  getIsDone();
                                },
                                child: Container(
                                  child: inputImg,
                                ),
                              ),
                            )
                          ],
                        ),
                      ),
                      SizedBox(height: 32.w,),
                      //邮箱
                      Container(
                        width: 670.w,
                        height: 108.w,
                        padding: EdgeInsets.symmetric(horizontal: 30.w),
                        decoration: BoxDecoration(
                            border: inputBorder,
                            borderRadius: BorderRadius.circular(20.w)
                        ),
                        child:  Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Expanded(child: TextField(
                              //控制器
                              textInputAction: TextInputAction.done,
                              controller: mailController,
                              maxLines: 1,
                              //是否自动更正
                              autocorrect: true,
                              //是否自动对焦
                              autofocus: false,
                              style:inputStyle,
                              inputFormatters: [

                              ],
                              decoration: InputDecoration(
                                contentPadding: const EdgeInsets.symmetric(vertical: 0,horizontal: 0),
                                hintText: mail_hintText.tr,
                                hintStyle: inputHitStyle,
                                counterText: "",
                                border: OutlineInputBorder(
                                    borderSide: BorderSide.none),
                              ),
                              onChanged: (val){
                                setState(() {
                                  mail = val.trim();
                                });
                                getIsDone();
                              },
                            )),
                            SizedBox(width: 20.w,),
                            Visibility(visible: mail!=null&&mail!.isNotEmpty,
                              child: GestureDetector(
                                onTap: (){
                                  setState(() {
                                    mailController.text = '';
                                    mail = null;
                                  });
                                  getIsDone();
                                },
                                child: Container(
                                  child: inputImg,
                                ),
                              ),
                            )
                          ],
                        ),
                      ),
                      SizedBox(height: 32.w,),
                      //验证码
                      Container(
                        width: 670.w,
                        height: 108.w,
                        child: Row(
                          children: [
                            Container(
                              width: 400.w,
                              height: 108.w,
                              padding: EdgeInsets.symmetric(horizontal: 30.w),
                              decoration: BoxDecoration(
                                  border: inputBorder,
                                  borderRadius: BorderRadius.circular(20.w)
                              ),
                              child:  Row(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  Expanded(child: TextField(
                                    //控制器
                                    textInputAction: TextInputAction.done,
                                    controller: codeController,
                                    keyboardType: TextInputType.number,
                                    maxLines: 1,
                                    maxLength: 6,
                                    //是否自动更正
                                    autocorrect: true,
                                    //是否自动对焦
                                    autofocus: false,
                                    style: inputStyle,
                                    inputFormatters: [
                                      FilteringTextInputFormatter.allow(RegExp("[0-9]"))
                                    ],
                                    decoration: InputDecoration(
                                      contentPadding: const EdgeInsets.symmetric(vertical: 0,horizontal: 0),
                                      hintText: validate_code_hintText.tr,
                                      hintStyle: inputHitStyle,
                                      counterText: "",
                                      border: OutlineInputBorder(
                                          borderSide: BorderSide.none),
                                    ),
                                    onChanged: (val){
                                      setState(() {
                                        code = val.trim();
                                      });
                                      getIsDone();
                                    },
                                  )),
                                  SizedBox(width: 20.w,),
                                  Visibility(visible: code!=null&&code!.isNotEmpty,
                                    child: GestureDetector(
                                      onTap: (){
                                        setState(() {
                                          codeController.text = '';
                                          code = '';
                                        });
                                        getIsDone();
                                      },
                                      child: Container(
                                        child: inputImg,
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            SizedBox(width: 24.w,),
                            GestureDetector(
                              onTap: (){
                                FocusScope.of(context).requestFocus(FocusNode());
                                getMsgCode();
                              },
                              child: Container(
                                width: 230.w,
                                height: 108.w,
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                    color: Color(0xff2B2B2B),
                                    borderRadius: BorderRadius.circular(16.w)
                                ),
                                child: Text(codeText,style: TextStyle(
                                    color: Colors.white,
                                    fontWeight: FontWeight.w600,
                                    fontSize: 28.sp
                                ),),
                              ),
                            )
                          ],
                        ),
                      ),
                      SizedBox(height: 32.w,),
                      //密码
                      Container(
                        width: 670.w,
                        height: 108.w,
                        padding: EdgeInsets.symmetric(horizontal: 30.w),
                        decoration: BoxDecoration(
                            border: inputBorder,
                            borderRadius: BorderRadius.circular(20.w)
                        ),
                        child:  Row(
                          children: [
                            Expanded(child: TextField(
                              //控制器
                              controller: passwordController,
                              // maxLength: 11,
                              maxLines: 1,
                              //是否自动更正
                              autocorrect: true,
                              //是否自动对焦
                              autofocus: false,
                              obscureText: isDisabled, //是否是密码
                              style: inputStyle,
                              decoration:  InputDecoration(
                                //                hintText: "请输入用户名",
                                contentPadding: EdgeInsets.zero,
                                hintText: pwd_hintText.tr,
                                hintStyle: inputHitStyle,
                                counterText: "",
                                border: const OutlineInputBorder(
                                    borderSide: BorderSide.none),
                              ),
                              onChanged: (val) {
                                setState(() {
                                  password = val.trim();
                                });
                                getIsDone();
                              },
                            )),
                            SizedBox(width: 20.w,),
                            GestureDetector(
                              onTap: (){
                                setState(() {
                                  isDisabled = !isDisabled;
                                });
                              },
                              child: Container(
                                child: Image.asset(!isDisabled?'assets/common/input_show.png':'assets/common/input_hide.png',width: 48.w,),
                              ),
                            )
                          ],
                        ),
                      ),
                      SizedBox(height: 40.w,),
                      //确认密码
                      Container(
                        height: 108.w,
                        width: 670.w,
                        padding: EdgeInsets.symmetric(horizontal: 30.w),
                        decoration: BoxDecoration(
                            border: inputBorder,
                            borderRadius: BorderRadius.circular(20.w)
                        ),
                        child:  Row(
                          children: [
                            Expanded(child: TextField(
                              //控制器
                              controller: surePasswordController,
                              // maxLength: 11,
                              maxLines: 1,
                              //是否自动更正
                              autocorrect: true,
                              //是否自动对焦
                              autofocus: false,
                              obscureText: isSureDisabled, //是否是密码
                              style: inputStyle,
                              decoration:  InputDecoration(
                                //                hintText: "请输入用户名",
                                contentPadding: EdgeInsets.zero,
                                hintText: ensure_pwd_hintText.tr,
                                hintStyle: inputHitStyle,
                                counterText: "",
                                border: const OutlineInputBorder(
                                    borderSide: BorderSide.none),
                              ),
                              onChanged: (val) {
                                setState(() {
                                  surePassword = val.trim();
                                });
                                getIsDone();
                              },
                            )),
                            SizedBox(width: 20.w,),
                            GestureDetector(
                              onTap: (){
                                setState(() {
                                  isSureDisabled = !isSureDisabled;
                                });
                              },
                              child: Container(
                                child: Image.asset(!isSureDisabled?'assets/common/input_show.png':'assets/common/input_hide.png',width: 48.w,),
                              ),
                            )
                          ],
                        ),
                      ),
                      SizedBox(height: 200.h,),
                      GestureDetector(
                        onTap: () {
                          FocusScope.of(context).requestFocus(FocusNode());
                          getIsDone();
                          if(isDone==false){
                            return;
                          }
                          _register();
                        },
                        child: Container(
                          height: 108.w,
                          width: 670.w,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              color: isDone? themeColor:themeBlueDisableColor,
                              borderRadius: BorderRadius.circular(20.w)
                          ),
                          child: Text('Continue'.tr,style: TextStyle(
                              color: Colors.white,
                              fontSize: 28.sp,
                              fontWeight: FontWeight.w600
                          ),),
                        ),
                      ),
                      SizedBox(height: 30.w,),
                      Container(
                        alignment: Alignment.center,
                        padding: EdgeInsets.symmetric(horizontal: 80.w),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Expanded(child: GestureDetector(
                              onTap: (){
                                FocusScope.of(context).requestFocus(FocusNode());
                                Navigator.of(context).pop();
                              },
                              child: Text(has_account.tr,style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 28.sp,
                                  fontWeight: FontWeight.w600
                              ),textAlign: TextAlign.center,),
                            )),
                            // GestureDetector(
                            //   onTap: (){
                            //     Navigator.of(context).pushNamed('RegisterPage',arguments: {
                            //       'type':2
                            //     });
                            //   },
                            //   child: Text('忘记密码',style: TextStyle(
                            //       color: themeColor,
                            //       fontSize: 26.sp,
                            //       fontWeight: FontWeight.w600
                            //   ),),
                            // )
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            )),
            SizedBox(height: ScreenUtil().bottomBarHeight > 0?ScreenUtil().bottomBarHeight:48.w,),
          ],
        ),
      ),
    );
  }
}
